<template>
  <div class="carModelSearchWrap commonSelectWidth table-page-search-wrapper">
    <a-form-model ref="formComp" :model="queryParams">
      <a-row :gutter="16">
        <a-col :xs="24" :sm="24" :md="24" :lg="4" :xl="4" :xxl="4">
          <!-- <a-input v-model="queryParams.vin" :placeholder="$t('pleaseInput') + 'VIN'" /> -->
          <a-select
            show-search
            v-model="queryParams.vin"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            :placeholder="$t('pleaseInput') + 'VIN'"
            @search="search"
            @focus="search"
            @change="onChange"
            allowClear
            :notFoundContent="isSearch? undefined : $t('noData') +'，'+ $t('ecuNameSearch')"
          >
            <a-spin
              v-if="isSearch"
              size="small"
              slot="notFoundContent"/>
            <a-select-option v-for="item in optionsPrincipal" :key="item.id" :value="item.vin">{{ item.vin }}</a-select-option>
          </a-select>
        </a-col>
        <!-- 车辆类型 -->
        <a-col :xs="24" :sm="24" :md="24" :lg="4" :xl="4" :xxl="4">
          <vehicle-type-select
            :default-value="queryParams.vehicleType"
            @changeoption="changeOption1($event, 'vehicleType')"
          ></vehicle-type-select>
        </a-col>
        <!-- 版本查询 -->
        <a-col :xs="24" :sm="24" :md="24" :lg="5" :xl="5" :xxl="5">
          <a-form-model-item :colon="false">
            <filter-box-collection
              :queryParam="queryParamsVersion"
              :placeholder="$t('bbcx')"
              @removetag="removeQueryKey1"
              @search="doAction('searchData')"
            >
              <template slot>
                <a-row style="padding-bottom:10px">
                  <a-select placeholder="DiLink版本" showSearch allowClear v-model="queryParams.dilinkVersion"
                            :defaultActiveFirstOption="false" @change="val => {queryParamsVersion.dilinkVersion=val;doAction('searchData')}">
                    <a-select-option v-for="item in diLinkVersionList" v-if="item" :key="item" :value="item" :title="item">{{item}}</a-select-option>
                  </a-select>
                </a-row>
                <a-row style="padding-bottom:10px">
                  <vehicle-version-name-type-select
                      ref="vehicleVersionRef"
                      mode="default"
                      :time="time"
                      :value="currentVehicleVersion"
                      @changeoption="(val) => {
                      queryParamsVersion.currentVehicleVersion=val;
                      queryParams.currentVehicleVersion=val;
                      doAction('searchData');}"
                    ></vehicle-version-name-type-select>
                </a-row>

              </template>
            </filter-box-collection>
          </a-form-model-item>
        </a-col>
        <!-- 高级查询 -->
        <a-col :xs="24" :sm="24" :md="24" :lg="5" :xl="5" :xxl="5">
          <a-form-model-item :colon="false">
            <filter-box-collection
              :queryParam="queryParamsDesc"
              @removetag="removeQueryKey"
              @search="doAction('searchData')"
            >
              <template slot>
                <!-- 品牌 -->
                <!-- <a-row style="padding-bottom:10px">
                  <a-select placeholder="品牌" allowClear v-model="queryParamsDesc.pinpai" @change="changeOption1($event, 'pinpai')">
                    <a-select-option v-for="item in brandList"  :key="item.id" :value="item.name">{{item.name}}</a-select-option>
                  </a-select>
                </a-row> -->
                <!-- 车辆类型 -->
                <!-- <a-row :gutter="48">
                  <a-col :md="24" :sm="24">
                    <a-form-model-item :label="$t('vehicleType')">
                      <vehicle-type-select
                        @changeoption="changeOption($event, 'vehicleType')"
                      ></vehicle-type-select>
                    </a-form-model-item>
                  </a-col>
                </a-row>-->
                <!-- 车系 -->
                <a-row :gutter="48">
                  <a-col :md="24" :sm="24">
                    <a-form-model-item >
                      <car-series-select
                        ref="carSeriesSelect"
                        mode="default"
                        :default-value="queryParams.brandId"
                        @changeoption="changeOption($event, 'brandId')"
                      ></car-series-select>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <!-- 车型 -->
                <a-row>
                  <car-model-code-select
                  mode="default"
                  :query="{ selectAll: false}"
                  :has-all="false"
                  :clear="true"
                  v-model="queryParams.modelCode"
                  @changeoption="(val,item) => {queryParamsDesc.modelCode = item ? item.showName : undefined;doAction('searchData')}"
                  style="width:100%;margin-bottom:10px"
                ></car-model-code-select>
                </a-row>
                <!-- 款型 -->
                <!-- <a-row :gutter="48">
                  <a-col :md="24" :sm="24">
                    <a-form-model-item >
                      <car-model-select
                        ref="carModelSelect"
                        mode="default"
                        :query="{ code: queryParams.modelCode}"
                        :has-all="false"
                        v-model="queryParams.modelIds"
                        :clear="true"
                        @changeoption="changeModels"
                      ></car-model-select>
                    </a-form-model-item>
                  </a-col>
                </a-row> -->
                <!-- 车辆版本 -->
                <!-- <a-row :gutter="48">
                  <a-col :md="24" :sm="24">
                    <a-form-model-item :label="$t('vehicleVersion')">
                      <vehicle-version-select
                        mode="default"
                        ref="vehicleVersionSelect"
                        :disabled="!queryParams.modelIds"
                        :time="queryVehicleVersionTime"
                        :query="{ modelId: queryParams.modelIds }"
                        :default-value="queryParams.vehicleVersion"
                        :replaceFields="{ id: 'id', value: 'name', title: 'name' }"
                        @changeoption="changeOption($event, 'vehicleVersion')"
                      ></vehicle-version-select>
                    </a-form-model-item>
                  </a-col>
                </a-row>-->
              </template>
            </filter-box-collection>
          </a-form-model-item>
        </a-col>
        <a-col :xs="24" :sm="24" :md="24" :lg="8" :xl="6" :xxl="6">
          <div class="searchBtns">
            <a-button-group>
              <auth-button
                type="primary"
                :auth="statisticsPerms.vehicle.view"
                @click="doAction('searchData')"
              >
                <i class="iconfont icon-chazhao"></i>
                {{ $t('inquiry') }}
              </auth-button>
              <a-button @click="clearCondition">
                <i class="iconfont icon-qingkong"></i>
                {{ $t('clear') }}
              </a-button>
            </a-button-group>
            <auth-button @click="exportVehicles"
                :auth="statisticsPerms.vehicle.export"
            >
              {{ $t('export') }}
            </auth-button>
            <!-- <auth-button :auth="managePerms.vehicle.add" @click="doAction('handleCreate')">
                         <i class="iconfont icon-xinjian"></i>
                         {{ $t('vehicle') }}
                       </auth-button>
                       <auth-button type="info" :auth="managePerms.vehicle.import" @click="doAction('handleImportFile')">
                         <i class="iconfont icon-wenjian"></i>
                         {{ $t('fileImport') }}
            </auth-button>-->
          </div>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
</template>
<script>
import FilterBoxCollection from '@/components/SelfComponents/FilterBoxCollection'
import VehicleTypeSelect from '@/views/components/VehicleTypeSelect'
import VehicleVersionSelect from '@/views/components/VehicleVersionSelect'
import CarModelSelect from '@/views/components/CarModelSelect.vue'
import CarSeriesSelect from '@/views/components/CarSeriesSelect.vue'
import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
import { mapState } from 'vuex'
import AuthButton from '@/components/AuthButton'
import { managePerms } from '@/config/permission/index'
import { statisticsPerms } from '@/config/permission/index'
import VehicleVersionNameTypeSelect from '@/views/components/VehicleVersionNameTypeSelect.vue'

import { axios } from '@/utils/request'
import statisticsApi from '@/api/modules/statistics'
import { downloadBlobFile } from '@/utils/functions'
import moment from 'moment'
import { debounce } from '@/utils/util'

const initQueryParams = {
  brandId: undefined,//车系
  modelIds: undefined,
  vehicleType: undefined,
  vehicleVersion: undefined,
  vin: '',
  modelCode:undefined
}
export default {
  components: {
    FilterBoxCollection,
    VehicleTypeSelect,
    CarModelSelect,
    VehicleVersionSelect,
    AuthButton,
    CarSeriesSelect,
    CarModelCodeSelect,
    VehicleVersionNameTypeSelect
  },
  computed: {
    ...mapState({
      queryParams: state => state.vehicle.queryParams,
    }),
    // 车辆版本
    selectedVehicleVersion () {
      return this.queryParams.currentVehicleVersion === null ? '' : this.queryParams.currentVehicleVersion
    },

  },
  created(){
    this.getDiLinkVersionList()
  },
  data() {
    return {
      managePerms,
      statisticsPerms,
      selectObj: {
        vehicleType: {
          fetch: 'getVehicleTypeName',
          data: null
        },
        modelIds: {
          fetch: 'getModelName',
          data: null
        },
        vehicleVersion: {
          fetch: 'getVehicleVersionName',
          data: null
        },
        brandId: {
          fetch: 'getBrandName',
          data: null
        }
      },
      queryParamsDesc: { ...initQueryParams },
      queryParamsVersion: {
        dilinkVersion: undefined,
        currentVehicleVersion: undefined
      },
      downloading: false,
      queryVehicleVersionTime: 0,
      optionsPrincipal: [],
      diLinkVersionList:[],
      exportingDetail: false,
      labelInValue: true,
      time: Date.now(),
      currentVehicleVersion: '',
      isSearch: false,
      lastFetchId: 0
    }
  },
  methods: {
    // vin模糊查询
    search(val = '') {
      this.isSearch = false
      this.optionsPrincipal = []
      this.lastFetchId += 1
      const fetchId = this.lastFetchId
      if (val) {
        this.isSearch = true
        this.getOptions(val, fetchId)
      }
    },
    onChange(val) {
      if (!val) {
        this.optionsPrincipal = []
      }
      this.doAction('searchData')
    },
    getOptions:debounce(function(search = '', fetchId) {
      this.queryParams.vin = search
      axios({
        url: '/vehicle-service/vehicle/findVehicleByVin',
        method: 'post',
        data: { vin: search }
      }).then(res => {
        console.log(fetchId, this.lastFetchId, '取最后一次')
        if (fetchId !== this.lastFetchId) {    
          return
        }
        if (res.code === 0) {
          this.optionsPrincipal = res.data
          this.isSearch = false
        } else {
          this.$message.warning(res.message)
          this.isSearch = false
        }
      })
    }, 400),
    getDiLinkVersionList(){
      axios({
        url: '/web-service/task/upgradeMonitor/getAllMediaVersionSet',
        method: 'get'
      }).then(res => {
        console.log(res)
        if (res.code==0) {
          this.diLinkVersionList=res.data
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleSearch() {
      this.$emit('search')
    },
    handleAdd() {
      this.$emit('handlecreate')
    },
    handleImport() {
      this.$emit('handleimport')
    },
    doAction(key, data) {

      console.log(key, data,this.queryParams,this.queryParamsDesc,this.queryParamsVersion);

      if (this[key]) {
        this[key](data || null)
        return
      }
      this.$emit('clickbtn', { type: key, data })
    },
    changeOption(val, key) {
      console.log(val, 'getBrandName1')
      this.queryParamsDesc[key] = this[this.selectObj[key].fetch](val)
      this.queryParams[key] = val
      this.doAction('searchData');
    },
    changeOption1(val, key) {
      this.queryParams[key] = val
      this.doAction('searchData');
    },
    // 获取车系文字
    getBrandName(val) {
      console.log(val, 'getBrandName2')
      if (this.selectObj.brandId.data === null) {
        this.selectObj.brandId.data = this.transfterArrayToObj(this.$refs.carSeriesSelect.options, 'id', 'name')
      }
      return this.selectObj.brandId.data[val]
    },
    // 获取车辆类型文字
    getVehicleTypeName(val) {
      if (this.selectObj.vehicleType.data === null) {
        this.selectObj.vehicleType.data = this.transfterArrayToObj(this.$store.state.vehicle.types, 'id', 'name')
      }
      return this.$t(this.selectObj.vehicleType.data[val])
    },
    // 获取车型名称
    getModelName(val) {
      console.log(val, 'val')
      if (this.selectObj.modelIds.data === null) {
        this.selectObj.modelIds.data = this.transfterArrayToObj(this.$refs.carModelSelect.modelOptions, 'id', 'name')
      }
      return this.selectObj.modelIds.data[val] || ''
    },
    // 获取车辆版本文字
    getVehicleVersionName(val) {
      if (this.selectObj.vehicleVersion.data === null) {
        this.selectObj.vehicleVersion.data = this.transfterArrayToObj(
          this.$refs.vehicleVersionSelect.options,
          'name',
          'name'
        )
      }
      return this.$t(this.selectObj.vehicleVersion.data[val])
    },
    transfterArrayToObj(arr, id, value) {
      const obj = {}
      arr.forEach(item => {
        obj[item[id]] = item[value]
      })
      return obj
    },
    // 删除搜索框中已选择的条件
    removeQueryKey(key) {

      console.log(key);

      if (this['remove' + key + 'Query']) {
        this['remove' + key + 'Query']()
      } else {
        this.queryParams[key] = undefined
        this.queryParamsDesc[key] = undefined
      }
    },
    removeQueryKey1(key) {

      console.log(key);
      if (this['remove' + key + 'Query']) {
        this['remove' + key + 'Query']()
      } else {
            this.queryParams[key] = null
            this.queryParamsVersion[key] = undefined
            this.time = Date.now()
      }

    },
    clearCondition () {
      // eslint-disable-next-line no-restricted-syntax
      for (const k in initQueryParams) {
        console.log(k, 'k')
        this.removeQueryKey(k)
      }
      this.queryParamsVersion={}
      this.queryParamsDesc={}
      this.$emit('clickbtn', { type: 'clearCondition' })
    },
    exportVehicles(){
       this.exportingDetail = true
       statisticsApi.exportVehicles(this.queryParams).then(res => {
         downloadBlobFile(res, '车辆信息列表-'+moment().format('YYYYMMDD-HHmmss')+'.xlsx')

       }).finally(() => {
         this.exportingDetail = false
       })
    },

    // 清除
    removedateQuery() {},
    // 修改车型
    changeModels(val, item) {
      // this.queryParams.modelIds = val
      this.queryParams.vehicleVersion = undefined
      this.queryParamsDesc.vehicleVersion = ''
      this.queryVehicleVersionTime = Date.now()
      // this.queryParamsDesc.modelIds = this.getModelName(val)
      this.queryParamsDesc.modelIds = item ? item.name : undefined;
      console.log('81813813813', 'this.queryParamsDesc.modelIds')
      this.doAction('searchData')
    },
    // 选择日期
    selectDate(val, dateString) {
      this.queryParamsDesc.dateBetween = dateString.join('~')
    }
  }
}
</script>
<style lang="less">
.carModelSearchWrap {
  /*padding: 0 24px;*/
  .ant-form-item-control {
    line-height: normal !important;
  }

  @media (max-width: 926px) {
    .searchBtns button {
      margin-top: 16px;
    }
  }
}
</style>
